from flask import Flask, render_template, request, jsonify
import os
import json
from create_json_files import CreateJsonFiles

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False

# 确保模板和静态文件目录存在
if not os.path.exists('templates'):
    os.makedirs('templates')
if not os.path.exists('static'):
    os.makedirs('static')

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/api/create_json', methods=['POST'])
def create_json():
    try:
        data = request.json
        
        # 获取表单数据
        class_type_index = int(data.get('class_type_index', 0))
        module = data.get('module', 'Login')
        prefix = data.get('prefix', 'CAT')
        class_desc = data.get('class_desc', '登录页')
        file_name = data.get('file_name', 'Test')
        
        # 获取子视图配置
        subviews = data.get('subviews', [])
        
        # 创建JSON文件
        creator = CreateJsonFiles()
        json_path = creator.create_json_with_config(
            type_index=class_type_index,
            subviews=subviews,
            file_name=file_name,
            module=module,
            prefix=prefix,
            class_desc=class_desc
        )
        
        return jsonify({
            'success': True,
            'message': f'JSON文件已创建: {json_path}',
            'path': json_path
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'创建JSON文件失败: {str(e)}'
        })

@app.route('/api/get_view_types')
def get_view_types():
    creator = CreateJsonFiles()
    return jsonify({
        'class_types': creator.get_class_types(),
        'view_types': creator.get_view_types()
    })

@app.route('/api/generate_swift', methods=['POST'])
def generate_swift():
    try:
        data = request.json
        json_path = data.get('json_path')
        
        # 导入GnnerateSwiftCode类
        from generate_uikit_code import GnnerateSwiftCode
        
        # 调用生成Swift代码的功能
        generator = GnnerateSwiftCode(json_path)
        
        # 假设生成的Swift文件保存在swift_codes目录下
        swift_file_name = os.path.basename(json_path).replace('.json', '.swift')
        swift_file_path = os.path.join('swift_codes', swift_file_name)
        
        return jsonify({
            'success': True,
            'message': f'Swift代码已生成: {swift_file_path}',
            'path': swift_file_path
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'生成Swift代码失败: {str(e)}'
        })

if __name__ == '__main__':
    app.run(debug=True, port=5001)